<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>data-filter</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
    </head>

    <body>
        <div id="app">
            <!-- 列表渲染过滤 -->
            <input type="text" placeholder="请输入关键字" v-model="keyword" />
            <ul>
                <li v-for="(person, index) in newPersons" :key="person.id">
                    {{person.id}} --- {{person.name}} --- {{person.age}}
                    <input :value="person.age" />
                </li>
            </ul>
            <!-- 如果定义的回调函数当中只有一行代码，可以不用写回调函数，直接写那一行代码 -->
            <button @click="sortType = 1">年龄升序</button>
            <button @click="sortType = 2">年龄降序</button>
            <button @click="sortType = 0">原样排序</button>
        </div>
        <script>
            new Vue({
                el: '#app',
                data() {
                    return {
                        sortType: 0, //0 原样  1 升序   2降序
                        keyword: '',
                        persons: [
                            { id: 1, name: 'zhaoliying', age: 33 },
                            { id: 2, name: 'yangmi', age: 34 },
                            { id: 3, name: 'qiwei', age: 40 },
                            { id: 4, name: 'dilireba', age: 20 },
                        ],
                    };
                },
                computed: {
                    // computed的对象模式中的get相当于函数式
                    newPersons: {
                        get() {
                            let { keyword, persons, sortType } = this;
                            let arr = persons.filter(
                                (item) => item.name.indexOf(keyword) !== -1
                            );
                            return arr;
                        },
                        set(val) {},
                    },
                },
                watch: {
                    // TODO:利用watch实现数据排序
                    //如果能够使用computed  就不要使用watch监控
                    sortType(newVal,oldValue) {
                        if(newVal !== 0) {
                            this.newPersons.sort((a,b) => {
                                return newVal === 1
                                ? a.age - b.age
                                : b.age - a.age;
                            });
                        };
                    },
                },
            });
        </script>
    </body>
</html>
